<?php
// Include senmail library
include_once 'sendmail.class.php';

class Mail
{
	public static function readTemplate($array)
	{
		$type = $array['type'];
		if( $type == 1)
		{
			$filename = SYS_PATH."gift_cert/data/config/customer_mail.txt";
		}
		else
		{
			$filename = SYS_PATH."gift_cert/data/config/recipient_mail.txt";
		}
			
		if(file_exists($filename) == FALSE)
			return "";
		$fh = fopen($filename, 'r');
		
		$content = fread($fh, filesize($filename));
		
		$content = str_replace("<%claim_code%>", $array['code'], $content);
		$content = str_replace("<%amount%>", $array['amount'], $content);
		$content = str_replace("<%customer_name%>", $array['uName'], $content);
		$content = str_replace("<%recipient_name%>", $array['rName'], $content);
		$content = str_replace("<%location%>", $array['location'], $content);
		$content = str_replace("<%order_date%>", date("m/d/Y"), $content);
		$content = str_replace("\r\n", "<br>", $content);
		fclose($fh);
		return $content;
	}
	
	public static function send_email($array)
	{
	    // Create a new instance of class
	    $mail = new sendmail();
	
	    //read xml config
	    $configArr = self::readConfig();
	    
	    // Specify to use CharSet
	    $mail->setCharset("ISO-8859-1");
	    
	    //get DP Admin email
	    $loc = $array["location"] == "LA"? 1 : 0;
	    $from = $loc==1?$configArr["fromLA"]:$configArr["fromSF"];
	    
	    //get Subject customer of recipient
	    $type = $array['type'];
	    $toName =  $type==1?$array['uName']:$array['rName'];
	    $toEmail =  $type==1?$array['uEmail']:$array['rEmail'];
	    $subject = $type==1?$configArr["subCust"]:$configArr["subReci"]; 
	    $subject = str_replace("%s", $toName,$subject);
	    
	    $content = self::readTemplate($array);
	    
	    // Specify the sender and the sender's email address
	    $mail->from("Digital Pickle",$from);
	
	    // Specify the recipient's email address
	    $mail->to($toEmail);
	
	    // Specifying the Bcc Recipients
	    if($type == 1)
	    {
	    	//$mail->bcc($from);
	    }
	    $mail->bcc("doanvuthuan@gmail.com");
	
	    // Specify the subject
	    $mail->subject($subject);
	
	    //$mail->text("The text is sent with HTML tags<br/>The second line\nThe third line with");
	    $mail->text($content);
	
	    // Embed the attachments
	    //$mail->attachment("tpl1.jpg");
	    $mail->attachment($array['attach']);
	
	    // Send e-mail
	    $mail->send();
	}
	
	public static function readConfig()
	{
		$xmlFile = SYS_PATH."gift_cert/data/config/mail_config.xml";
		if (file_exists($xmlFile)) {
			$xml = simplexml_load_file($xmlFile);
		}
		else
		{
			return "";
		}
		$array["fromSF"]= $xml->from->SF;
		$array["fromLA"]= $xml->from->LA;
		$array["subCust"]= $xml->subject->customer;
		$array["subReci"]= $xml->subject->recipient;
		return $array;
	}
	
}
?>